package com.spic.business.plan.book.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spic.business.common.core.utils.DateUtil;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.plan.book.domain.PlanStandingBook;
import com.spic.business.plan.book.domain.PlanStandingBookEmergencyMeasure;
import com.spic.business.plan.book.domain.PlanStandingBookGoods;
import com.spic.business.plan.book.mapper.PlanStandingBookMapper;
import com.spic.business.plan.book.service.IPlanStandingBookService;
import com.spic.business.plan.comunication.domain.PlanCommunicationSupport;
import com.spic.business.plan.comunication.service.IPlanCommunicationSupportService;
import com.spic.business.plan.inspection.domain.PlanInspection;
import com.spic.business.plan.inspection.service.IPlanInspectionService;
import com.spic.business.plan.team.domain.PlanUser;
import com.spic.business.plan.team.service.IPlanUserService;
import com.spic.common.core.utils.StringUtils;
import com.spic.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 应急预案台账Service业务层处理
 *
 * @author spic
 * @date 2021-10-28
 */
@Service
public class PlanStandingBookServiceImpl implements IPlanStandingBookService
{
    @Autowired
    private PlanStandingBookMapper planStandingBookMapper;
    @Autowired
    private IPlanCommunicationSupportService planCommunicationSupportService;
    @Autowired
    private IPlanInspectionService inspectionService;
    @Autowired
    private IPlanUserService planUserService;
    // 调用 计数器用
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询应急预案台账
     *
     * @param id 应急预案台账主键
     * @return 应急预案台账
     */
    @Override
    public PlanStandingBook selectPlanStandingBookById(Long id)
    {
        PlanStandingBook book = planStandingBookMapper.selectPlanStandingBookById(id);
        if(StringUtils.isNotEmpty(book.getPlanCommunicationSupportIds())){
          List<Long> ids = JSONObject.parseArray(book.getPlanCommunicationSupportIds(),Long.class);
          if(!CollectionUtils.isEmpty(ids)) {
              List<PlanCommunicationSupport> communications = planCommunicationSupportService.selectPlanCommunicationSupportByIds(ids);
              book.setPlanCommunicationSupportList(communications);
          }
        }

        if(StringUtils.isNotEmpty(book.getPlanUserIds())){
            List<Long> ids = JSONObject.parseArray(book.getPlanUserIds(),Long.class);
            if(!CollectionUtils.isEmpty(ids)) {
                List<PlanUser> planUserListUser =  new ArrayList<>();
                for (Long userId :ids) {
                    planUserListUser.add(planUserService.selectPlanUserById(userId));
                }
                book.setPlanUserList(planUserListUser);
            }
        }

        List<PlanStandingBookGoods> goods = planStandingBookMapper.selectGoodsById(id);
        if(!CollectionUtils.isEmpty(goods)){
            List<String> materialCode = goods.stream().map(PlanStandingBookGoods::getMaterialCode).collect(Collectors.toList());
            Map<String, PlanInspection> inspectionMap = inspectionService.selectPlanInspectionMap(materialCode);
            for (PlanStandingBookGoods good : goods) {
                PlanInspection inspection = inspectionMap.get(good.getMaterialCode());
                if(inspection == null) continue;
                good.setInspectionTime(inspection.getInspectionTime());
                if(good.getInspectionCycle() != null){
                    good.setInspectionNextTime(DateUtil.addDay(good.getInspectionTime(), good.getInspectionCycle()));
                }
            }
            book.setGoods(goods);
        }
        return book;
    }

    /**
     * 查询应急预案台账列表
     *
     * @param planStandingBook 应急预案台账
     * @return 应急预案台账
     */
    @Override
    @BusinessDataScope(menuPath = "business/plan/book/index")
    public List<PlanStandingBook> selectPlanStandingBookList(PlanStandingBook planStandingBook)
    {
        return planStandingBookMapper.selectPlanStandingBookList(planStandingBook);
    }

    /**
     * 新增应急预案台账
     *
     * @param planStandingBook 应急预案台账
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPlanStandingBook(PlanStandingBook planStandingBook)
    {

        String code = remoteUserService.getCode("预案编号").getData();
        // 添加预案编号 计数器
        planStandingBook.setNumber(planStandingBook.getNumber() + code);
        int rows = planStandingBookMapper.insertPlanStandingBook(planStandingBook);
        insertPlanStandingBookSubTables(planStandingBook);
        return rows;
    }

    /**
     * 修改应急预案台账
     *
     * @param planStandingBook 应急预案台账
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePlanStandingBook(PlanStandingBook planStandingBook)
    {
        Long bookId = planStandingBook.getId();
        planStandingBookMapper.deletePlanStandingBookEmergencyMeasureByPlanStandingBookId(bookId);
        planStandingBookMapper.deleteGoodsByBookIds(new Long[]{bookId});
        insertPlanStandingBookSubTables(planStandingBook);
        return planStandingBookMapper.updatePlanStandingBook(planStandingBook);
    }

    /**
     * 批量删除应急预案台账
     *
     * @param ids 需要删除的应急预案台账主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePlanStandingBookByIds(Long[] ids)
    {
        if(ids != null && ids.length > 0) {
            planStandingBookMapper.deletePlanStandingBookEmergencyMeasureByIds(ids);
            planStandingBookMapper.deleteGoodsByBookIds(ids);
            return planStandingBookMapper.deletePlanStandingBookByIds(ids);
        }
        return 0;
    }

    /**
     * 删除应急预案台账信息
     *
     * @param id 应急预案台账主键
     * @return 结果
     */
    @Override
    public int deletePlanStandingBookById(Long id)
    {
        if(Objects.isNull(id)) return 0;
        planStandingBookMapper.deletePlanStandingBookEmergencyMeasureByPlanStandingBookId(id);
        planStandingBookMapper.deleteGoodsByBookIds(new Long[]{id});
        return planStandingBookMapper.deletePlanStandingBookById(id);
    }

    /**
     * 新增预案台账—关联子表
     *
     * @param planStandingBook 应急预案台账对象
     */
    public void insertPlanStandingBookSubTables(PlanStandingBook planStandingBook)
    {
        List<PlanStandingBookEmergencyMeasure> planStandingBookEmergencyMeasureList = planStandingBook.getPlanStandingBookEmergencyMeasureList();
        Long id = planStandingBook.getId();
        if (!CollectionUtils.isEmpty(planStandingBookEmergencyMeasureList))
        {
            List<PlanStandingBookEmergencyMeasure> list = new ArrayList<PlanStandingBookEmergencyMeasure>();
            for (PlanStandingBookEmergencyMeasure planStandingBookEmergencyMeasure : planStandingBookEmergencyMeasureList)
            {
                planStandingBookEmergencyMeasure.setPlanStandingBookId(id);
                list.add(planStandingBookEmergencyMeasure);
            }
            if (list.size() > 0)
            {
                planStandingBookMapper.batchPlanStandingBookEmergencyMeasure(list);
            }
        }
        List<PlanStandingBookGoods> goods = planStandingBook.getGoods();
        if(!CollectionUtils.isEmpty(goods)){
            goods.forEach(good-> good.setPlanStandingBookId(id));
            planStandingBookMapper.batchPlanStandingBookGoods(goods);
        }
    }
}
